package com.tanhua.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;


/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: SmsTemplate
 * @Author:王晨晗
 * @Description: 短信模板类
 * @Date: 2021/12/25/21:21
 */
public class SmsTemplate {
    private SmsProperties smsProperties;

    public SmsTemplate(SmsProperties smsProperties){
        this.smsProperties = smsProperties;
    }

    //发送短信验证码
    public String sendSms(String mobile){
        DefaultProfile profile = DefaultProfile.getProfile(smsProperties.getRegionId(),
                smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        //随机生成6位数字验证码
        String code= RandomUtils.nextInt(100000, 999999) + "";
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsProperties.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", smsProperties.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", smsProperties.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}
            System.out.println(response.getData());
            //判断短信发送的状态是否正确 , 决定返回null 还是 code
            return !StringUtils.contains(response.getData(),"\"Message\":\"OK\"") ? null : code;
        } catch (Exception e) {
            return null;
        }
    }

}
